package operators

import (
	db "babydoge/config/db"
	"babydoge/enum/fileds"
	"babydoge/models"
	"babydoge/processor"
	"gorm.io/gorm"
)

func Run() (err error) {
	var (
		dataBase *db.DB
		result   *gorm.DB
		queues   []models.Queue
		queue    models.Queue
		jobEvent *processor.JobEvent
	)

	//连接数据库
	if dataBase, err = db.NewDB(); err != nil {
		return err
	}

	//将查出来的未处理的重新放入
	result = dataBase.Db.Where("status = ?", fileds.Unexecuted).Find(&queues)
	if result.Error == nil {
		for _, queue = range queues {
			jobEvent = &processor.JobEvent{
				EventType: processor.JOB_EVENT_SAVE,
				Job: &processor.Job{
					Name:    queue.ID,
					Command: queue.Command,
					RunAt:   queue.RunAt,
				},
			}
			processor.G_scheduler.HandleJobEvent(jobEvent)
		}
		return err
	}

	return err

}
